#!/bin/bash

# Supported features
# usehwvolume:  use the hardware volume control instead of DSP volume control if both controls are available
# bluetooth: hardware supports bluetooth
# pi3orlater: Pi3 or Pi4
# arm7: arm7 or higher CPU generation
# spdifnoclock: card has an SPDIF input, but requires Pi clock generation
# toslink: card has a TOSLink input
# analoginput: card has an analog input
# digi: card is a digital sound card
# dsp: DSP available
# localui: Local UI web browser supported

REBOOTFILE=/tmp/reboot
SERVICES="spotify raat mpd shairport-sync squeezelite bluealsa-aplay alsaloop dlnampris mopidy upmpdcli"
FEATURES="pi"
SET_VOLUMERANGE=""

# If there's a fix-config-script, run it, there might be some updates necessary after an update
if [ -f /opt/hifiberry/bin/after-update ]; then
 /opt/hifiberry/bin/after-update
fi

# Check that UUID exists
if [ ! -s "/etc/uuid" ]; then
 /usr/bin/uuidgen > /etc/uuid
fi

if [ ! -d /etc/features ]; then
 # Looks like a fresh installation or update, 
 # reconfigure everything
 if [ -f /etc/hifiberry.state ]; then
   mv /etc/hifiberry.state /etc/hifiberry.state.bak
 fi
 mkdir /etc/features
fi 

read_features() {
 for dir in /etc/hifiberry /custom/hifiberry; do
   if [ -d $dir ]; then 
     pushd $dir >/dev/null
     for f in *.feature; do
       if [ "$f" != "*.feature" ]; then
         F=${f/.feature/}
         FEATURES="$FEATURES $F"
         eval "FEATURE_$F=1"
       fi 
     done
   popd >/dev/null
   fi
 done
}

restart_service() {
 systemctl is-active --quiet $1
 if [ "$?" == "0" ]; then
   echo "Restarting $1"
   systemctl restart $1
 fi
}

read_fixed() {
 if [ -f /etc/hifiberry/config.fixed ]; then
  . /etc/hifiberry/config.fixed
  for N in MIXER_CONTROL CARD FEATURES; do
    $N=${CURRENT_$N}
  done
 fi
}

check_systemd() {
 SERVICE_ACTIVE=0
 for SERVICE in "$@"; do 
   systemctl is-active --quiet $SERVICE
   if [ "$?" == "0" ]; then
     SERVICE_ACTIVE=1
   fi

   systemctl is-enabled --quiet $SERVICE 
   if [ "$?" == "0" ]; then
     SERVICE_ACTIVE=1
   fi 
   
 done
}

# Detect USB devices that HiFiBerryOS supports 
usb_devices() {
  FOUND_USBBT=`readlink /sys/bus/usb/devices/*/driver | grep btusb`
  if [ "$FOUND_USBBT" != "" ]; then
    FEATURES="$FEATURES bluetooth"
  fi
}

# Detect Raspberry Pi model
pi_model() {
 modelname=$(tr -d '\0' < /proc/device-tree/model)

 if [[ $modelname == *"3 Model B+"* ]]; then
  PIMODEL="3B+"
  PIVERSION=3
  FEATURES="$FEATURES bluetooth pi3orlater arm7"
  return
 fi 

 if [[ $modelname == *"3 Model B Plus"* ]]; then
  PIMODEL="3B+"
  PIVERSION=3
  FEATURES="$FEATURES bluetooth pi3orlater arm7"
  return
 fi

 if [[ $modelname == *"3 Model A Plus"* ]]; then
  PIMODEL="3A+"
  PIVERSION=3
  FEATURES="$FEATURES bluetooth pi3orlater arm7"
  return
 fi

 if [[ $modelname == *"3 Model B"* ]]; then
  PIMODEL="3B"
  PIVERSION=3
  FEATURES="$FEATURES pi3orlater arm7"
  return
 fi 

 if [[ $modelname == *"4 Model B"* ]]; then
  PIMODEL="4"
  PIVERSION=4
  FEATURES="$FEATURES bluetooth pi3orlater arm7"
  return
 fi
 
 if [[ $modelname == *"Compute Module 4"* ]]; then
  PIMODEL="4"
  PIVERSION=4
  FEATURES="$FEATURES bluetooth pi3orlater arm7"
  return
 fi

 if [[ $modelname == *"Pi Zero W"* ]]; then
  PIMODEL="0w"
  PIVERSION=0
  FEATURES="$FEATURES bluetooth"
  return
 fi
 
 if [[ $modelname == *"Pi Zero 2"* ]]; then
  PIMODEL="02w"
  PIVERSION=3
  FEATURES="$FEATURES bluetooth pi3orlater arm7"
  return
 fi

 if [[ $modelname == *"Pi 2 Model"* ]]; then
  PIMODEL="2"
  PIVERSION=2
  FEATURES="$FEATURES arm7"
  return
 fi

 PIMODEL="unknown" 
}

fix_asound_hw() {
 if [ "$HW_SHORT" == "" ]; then
  echo "no HiFiBerry sound card detected, not changing /etc/asound.conf"
  return
 fi
 sed -i "s/card\s[0-9]/card\ $HW_SHORT/g" /etc/asound.conf
}

# Find the correct input and output hardware devices
# this is important if additional USB hardware is connected
detect_hw () {
 HW=`aplay -l | grep hifiberry | awk -F: '{print $1}'`
 HW_SHORT=`echo $HW | awk '{print $2}'`
 fix_asound_hw
}

# Find the correct ALSA volume control 
guess_volume_control() {
 if [ "$MIXER_CONTROL" != "" ]; then
   echo "Using fixed mixer control $MIXER_CONTROL"
   return
 fi
	
 if [ -f /etc/hifiberry/mixer ]; then
   MIXER_CONTROL=`cat /etc/hifiberry/mixer`
   if [ "MIXER_CONTROL" != "" ]; then
     return
   fi
 fi

 # If a DSP module was detected, check for DSP volume
 # control first
 if [[ $CARD == *"DSP"* ]]; then
   dsptoolkit --timeout=20 get-volume 2 >/dev/null >/dev/null
   if [ $? == 0 ]; then
     MIXER_CONTROL=DSPVolume
     return
   fi
 fi

 # DAC2 HD used "DAC"
 DAC=`amixer scontrols | grep "'DAC',"`
 if [ "$DAC" != "" ]; then
   MIXER_CONTROL=DAC
   return
 fi

 # DAC+ and Amp2 use "Digital"
 DIGITAL=`amixer scontrols | grep Digital`
 if [ "$DIGITAL" != "" ]; then
   MIXER_CONTROL=Digital
   return
 fi

 # Amp3 uses "A.Mstr Vol"
 MSTRVOL=`amixer scontrols | grep "A.Mstr Vol"`
 if [ "$MSTRVOL" != "" ]; then
   MIXER_CONTROL="A.Mstr Vol"
   return
 fi

 # Amp+ uses "Master"
 # however, as shairport-sync doen't work with this, we'll use softvol
 MASTER=`amixer scontrols | grep Master`
 if [ "$MASTER" != "" ]; then
   MIXER_CONTROL=Softvol
   return
 fi

 # Check if there is a working DSP volume control
 dsptoolkit --timeout=20 get-volume 2 >/dev/null >/dev/null
 if [ $? == 0 ]; then
    MIXER_CONTROL=DSPVolume
    return
 fi

 # There should be at least a Softvol control
 SOFTVOL=`amixer scontrols | grep Softvol`
 if [ "$SOFTVOL" != "" ]; then
   MIXER_CONTROL=Softvol
   return
 fi

 echo "Could not find ALSA volume control, just using softvol"
 MIXER_CONTROL=Softvol
}

# Guess what card is installed"
guess_card() {
 if [ "$CARD" != "unknown" ] && [ "$CARD" != "" ]; then
  echo "Using fixed card $CARD with fetaures $FEATURES"
  return
 fi

 check_dsp
 hat_info

 INTPIN=2 # By default use RX pin for interrupts of the power controller

 if [ "$HATINFO" == "HiFiBerry Digi2 Pro" ]; then
  if [ "$HAS_DSP" == "1" ]; then
     CARD="Digi2 Pro + DSP Module"
     DSPTYPE="DSP add-on"
     SECONDARY_MIXER_CONTROL="Softvol"
   else
     CARD="Digi2 Pro"
   fi
   return
 fi

 if [ "$HATINFO" == "HiFiBerry Amp100" ]; then
  if [ "$HAS_DSP" == "1" ]; then
     CARD="Amp100 + DSP Module"
     DSPTYPE="DSP add-on"
     FEATURES="$FEATURES spdifnoclock toslink"
     SECONDARY_MIXER_CONTROL="Digital"
   else
     CARD="Amp100"
   fi
   INTPIN=3
   return
 fi

 if [ "$HATINFO" == "HiFiBerry Amp3" ]; then
  if [ "$HAS_DSP" == "1" ]; then
     CARD="Amp3 + DSP Module"
     DSPTYPE="DSP add-on"
     SECONDARY_MIXER_CONTROL="A.Mstr Vol"
   else
     CARD="Amp3"
     FEATURE_usehwvolume=1
   fi
   if [ "$FEATURE_usehwvolume" == "1" ]; then
     SET_VOLUMERANGE="[50,100]"
   else
     SET_VOLUMERANGE="[0,100]"
   fi
   INTPIN=3
   return
 fi

 if [ "$HATINFO" == "HiFiBerry Amp4" ]; then
  if [ "$HAS_DSP" == "1" ]; then
     CARD="Amp4 + DSP Module"
     DSPTYPE="DSP add-on"
     SECONDARY_MIXER_CONTROL="Digital"
   else
     CARD="Amp4"
     FEATURE_usehwvolume=1
   fi
   INTPIN=3
   return
 fi

 DAC2HD=`aplay -l | grep hifiberry_dacplushd`
 if [ "$DAC2HD" != "" ]; then
   if [ "$HAS_DSP" == "1" ]; then
     CARD="DAC2 HD + DSP Module"
     DSPTYPE="DSP add-on"
     SECONDARY_MIXER_CONTROL="DAC"
   else
     CARD="DAC2 HD"
   fi
   return
 fi

 DACPLUSADCPRO=`aplay -l | grep DAC+ | grep ADC | grep Pro`   
 if [ "$DACPLUSADCPRO" != "" ]; then                          
   CARD="DAC+ ADC Pro"
   FEATURES="$FEATURES analoginput"
   return                                                     
 fi                                                           
                                                              
 DACPLUSADC=`aplay -l | grep DAC+ | grep ADC`                 
 if [ "$DACPLUSADC" != "" ]; then                             
   CARD="DAC+ ADC"                                            
   FEATURES="$FEATURES analoginput"
   return                                                     
 fi                                                           
        
 DACPRO=`aplay -l | grep DAC+ | grep Pro`
 if [ "$DACPRO" != "" ]; then
   if [ "$HAS_DSP" == "1" ]; then
     CARD="DAC2 Pro + DSP Module"
     DSPTYPE="DSP add-on"
     SECONDARY_MIXER_CONTROL="Digital"
   else
     amixer sget Headphone 2>/dev/null >/dev/null
     if [ $? == 0 ]; then
       CARD="DAC2 Pro"
       # Fix headphone volume for now
       amixer sset Headphone 0db
     else
       CARD="DAC+ Pro"
     fi
   fi
   return
 fi

 DACDSP=`aplay -l | grep DAC+DSP`
 if [ "$DACDSP" != "" ]; then
   CARD="DAC+ DSP"
   FEATURES="$FEATURES toslink"
   return
 fi

 DAC=`aplay -l | grep DAC+`
 if [ "$DAC" != "" ]; then
   CARD="DAC+/Amp2"
    return
 fi

 AMPPLUS=`aplay -l | grep AMP`
 if [ "$AMPPLUS" != "" ]; then
   CARD="Amp+"
   return
 fi

 DIGIPRO=`aplay -l | grep Digi | grep Pro`
 if [ "$DIGIPRO" != "" ]; then
   CARD="Digi+ Pro"
   FEATURES="$FEATURES digi"
   return
 fi

 DIGI=`aplay -l | grep Digi`
 if [ "$DIGI" != "" ]; then
   CARD="Digi+"
   FEATURES="$FEATURES digi" 
   return
 fi

 CLKGEN=`i2cget -y 1 0x60 2 2>/dev/null`
 if [ "$CLKGEN" == "0x03" ]; then
    CARD="Beocreate 4-Channel Amplifier"
    INTPIN=1
    if  [ "${FEATURES/dsp/}" == "$FEATURES" ]; then
      FEATURES="$FEATURES dsp"
    fi
    FEATURES="$FEATURES toslink"
    return
 fi

 if [ "$HATINFO" == "no vendor no product" ]; then
   if [ "$HAS_DSP" == "1" ]; then
     # A card with an empty HAT EEPROM and a DSP is probably a Beocreate
     CARD="Beocreate 4-Channel Amplifier"
     INTPIN=1
     if  [ "${FEATURES/dsp/}" == "$FEATURES" ]; then
       FEATURES="$FEATURES dsp"
     fi
     FEATURES="$FEATURES toslink"
     return
   fi 
 fi

 if [ "$HATINFO" == "HiFiBerry Beocreate 4CA" ]; then
    CARD="Beocreate 4-Channel Amplifier"
    INTPIN=1
    if  [ "${FEATURES/dsp/}" == "$FEATURES" ]; then
      FEATURES="$FEATURES dsp"
    fi
    if  [ "${FEATURES/toslink/}" == "$FEATURES" ]; then
      FEATURES="$FEATURES toslink"
    fi
    return
 fi

 if [ "$HAS_DSP" == "1" ]; then
    CARD="DAC+ DSP"
    FEATURES="$FEATURES toslink"
    return
 fi

 # If nothing was detected, it might be a DAC+ Light/Zero or MiniAmp"
 CARD="DAC+ Zero/Light/MiniAmp"
}

check_dsp() {
 if [ -f /etc/hifiberry/has_dsp ]; then
   HAS_DSP=1
   FEATURES="$FEATURES dsp"
   return
 fi

 # try using metadata
 DETECTED=`dsptoolkit --timeout=20 get-meta detected_dsp`
 if [ "$DETECTED" != "" ]; then
   HAS_DSP=1
   FEATURES="$FEATURES dsp"
 else
   HAS_DSP=0
 fi

 if [ "$HAS_DSP" == "0" ]; then
   # DSP detection sometimes does not work correctly, try to read data from
   # the DSP
   MEM=`dsptoolkit --timeout=4 read-hex 0x01 | awk '{print $1 $2 $3 $4}'`
   if [ "$MEM" != "00000000" ] && [ "$MEM" != "FFFFFFFF" ]; then
     echo 1 $MEM 2
     HAS_DSP=1
     FEATURES="$FEATURES dsp"
   fi
 fi

 # If a DSP was detected, make sure, it knows the profile
 if [ "$HAS_DSP" == "1" ]; then
   if [ -x /opt/hifiberry/bin/fix-dsp-profile ]; then
     /opt/hifiberry/bin/fix-dsp-profile force
   fi
 fi
}

check_genuine() {
 /bin/true 
}

# Get HAT information
hat_info() {
 HATINFO=`/opt/hifiberry/bin/readhat | sed s/:/\ /`
}

# Calculate system names
system_name() {
 if [ -f /etc/systemname ]; then
   SYSNAME=`cat /etc/systemname`
 else
   SYSNAME=""
 fi

 if [ "$SYSNAME" == "" ]; then 
   SYSNAME=HiFiBerry
   echo $SYSNAME > /etc/systemname
 fi

 SYSNAME_NO_SPACES=`echo $SYSNAME | sed s/\ /-/g`
 SYSNAME_SED_SPACES=`echo $SYSNAME | sed 's/\ /\\\\\\ /g'` 
}

# Pi3 A+ hasn't enough RAM for local UI
check_pi3a() {
  if [ "$PIMODEL" == "3A+" ]; then
    # Pi 3A+ can't run a local UI as it doesn't have enough RAM
    FEATURES=${FEATURES/localui/}
    systemctl disable weston cog
  fi
}

# Reconfigure SpotifyD
reconfigure_spotify() {
 if [ ! -f /etc/spotifyd.conf ]; then
  echo "spotifyd not installed, ignoring"
  return
 fi

 RESTART=0
 if [ "$MIXER_CONTROL" != "$CURRENT_MIXER_CONTROL" ]; then
  sed -i "s/mixer\ =.*/mixer\ =\ $MIXER_SED_SPACES/" /etc/spotifyd.conf 
  RESTART=1
  echo " updated mixer"
 fi

 if [ "$SYSNAME" != "$CURRENT_SYSNAME" ]; then
  sed -i s/device_name\ =.*/device_name\ =\ $SYSNAME_NO_SPACES/ /etc/spotifyd.conf
  RESTART=1
  echo " updated system name"
 fi

 if [ "$RESTART" == "1" ]; then
  restart_service spotify
 fi
}

# Reconfigure Vollibrespot
reconfigure_vollibrespot() {
 if [ ! -f /etc/vollibrespot.conf ]; then
  echo "vollibrespot not installed, ignoring"
  return
 fi

 RESTART=0
 if [ "$MIXER_CONTROL" != "$CURRENT_MIXER_CONTROL" ]; then
  sed -i "s/mixer-name\ =.*/mixer-name\ =\ \'$MIXER_SED_SPACES\'/" /etc/vollibrespot.conf
  RESTART=1
  echo " updated mixer"
 fi

 if [ "$SYSNAME" != "$CURRENT_SYSNAME" ]; then
  sed -i s/device-name\ =.*/device-name\ =\ \'$SYSNAME\'/ /etc/vollibrespot.conf
  RESTART=1
  echo " updated system name"
 fi

 if [ "$HW" != "$CURRENT_HW" ]; then
  sed -i s/mixer-card\ =.*/mixer-card\ =\ \'hw:$HW_SHORT\'/ /etc/vollibrespot.conf
  RESTART=1
  echo " updated mixer-card"
 fi

 if [ "$RESTART" == "1" ]; then
  restart_service spotify
 fi
}

# Reconfigure Shairport-sync
reconfigure_shairport() {
 if [ ! -f /etc/shairport-sync.conf ]; then
  echo "shairport-sync not installed, ignoring"
  return
 fi

 RESTART=0
 if [ "$MIXER_CONTROL" != "$CURRENT_MIXER_CONTROL" ]; then
  sed -i "s/mixer_control_name\ =\ .*/mixer_control_name\ =\ \"$MIXER_SED_SPACES\"\;/" /etc/shairport-sync.conf 
  RESTART=1
  echo " updated mixer"
 fi
 if [ "$SYSNAME" != "$CURRENT_SYSNAME" ]; then
  sed -i s/\ name\ =\ .*/\ name\ =\ \"$SYSNAME\"\;/ /etc/shairport-sync.conf  
  RESTART=1
  echo " updated system name"
 fi
 if [ "$RESTART" == "1" ]; then
  restart_service shairport-sync
 fi
}

# Reconfigure AudioControl2
reconfigure_audiocontrol2() {
 RESTART=0
 if [ "$MIXER_CONTROL" != "$CURRENT_MIXER_CONTROL" ]; then
  sed -i "s/mixer_control=.*/mixer_control=$MIXER_SED_SPACES/" /etc/audiocontrol2.conf
  RESTART=1
  echo " updated mixer"
 fi

 if [ "$CURRENT_INTPIN" != "$INTPIN" ]; then
  sed -i s/intpin=.*/intpin=$INTPIN/ /etc/audiocontrol2.conf
  echo " updated interrupt pin"
  RESTART=1
 fi

 if [ "$RESTART" == "1" ]; then
  restart_service audiocontrol2
 fi
}


# Reconfigure Bluetooth
reconfigure_bluetooth() {
 BT=`echo $FEATURES | grep bluetooth`
 if [ "$SYSNAME" != "$CURRENT_SYSNAME" ]; then
  sed -i "s/Name\ =\ .*/Name\ =\ $SYSNAME_SED_SPACES/" /etc/bluetooth/main.conf
  RESTART_BT=1
  echo " updated system name"
 fi
 if [ "$MIXER_CONTROL" != "$CURRENT_MIXER_CONTROL" ]; then
  RESTART_BT=1
  echo " updated mixer"
 fi
 if [ "$RESTART_BT" == "1" ]; then
  restart_service bluetooth.service
 fi
}

# Reconfigure squeezelite
reconfigure_squeezelite() {
 if [ "$SYSNAME" != "$CURRENT_SYSNAME" ]; then
  echo $SYSNAME > /var/squeezelite/squeezelite.name
  restart_service squeezelite
  echo " updated system name"
 fi
}

# Reconfigure dlnampris
reconfigure_dlna() {
 if [ ! -f /etc/dlnampris.conf ]; then
  echo "dlna-mpris not installed, ignoring"
  return
 fi

 UPDATED=0
 if [ "$SYSNAME" != "$CURRENT_SYSNAME" ]; then
  sed -i "s/systemname\=.*/systemname=$SYSNAME_SED_SPACES/" /etc/dlnampris.conf
  UPDATE=1
 fi

 if [ "$MIXER_CONTROL" != "$CURRENT_MIXER_CONTROL" ]; then
  sed -i "s/mixer\=.*/mixer=$MIXER_SED_SPACES/" /etc/dlnampris.conf
  UPDATE=1
 fi

 restart_service dlna-mpris
}

# Reconfigure MPD
reconfigure_mpd() {
 if [ ! -f /etc/mpd.conf ]; then
  echo "mpd not installed, ignoring"
  return
 fi

 if [ "$MIXER_CONTROL" != "$CURRENT_MIXER_CONTROL" ]; then
  sed -i "s/mixer_control\ .*/mixer_control\ \ \ \"$MIXER_SED_SPACES\"/" /etc/mpd.conf
  restart_service mpd
  echo " updated mixer"
 fi
}

# Reconfigure upmpdcli
reconfigure_upmpdcli() {
 if [ ! -f /etc/upmpdcli.conf ] ; then return; fi

 if [ "$CURRENT_SYSNAME" != "$SYSNAME" ]; then
  sed -i s/friendlyname.*/friendlyname\ =\ $SYSNAME/ /etc/upmpdcli.conf
  sed -i s/url=.*.local/url=http:\\/\\/$SYSNAME_NO_SPACES.local/ /etc/upmpdcli.html
  restart_service upmpdcli
  echo " updated system name"
 fi
}

# Reconfigure RAAT
reconfigure_raat() {
 if [ ! -d /opt/raat ]; then
  echo "RAAT not installed, ignoring"
  return
 fi
 /opt/raat/configure-raat
}


# Reconfigure Beocreate 
reconfigure_beocreate() {
 UPDATE=0
 # Update card type
 if [ "$CARD" != "$CURRENT_CARD" ]; then
  /bin/node /opt/beocreate/beo-system/configure.js system cardType "$CARD"
  echo " updated card type"
  UPDATE=1
 fi

 # Update mixer control
 if [ "$MIXER_CONTROL" != "$CURRENT_MIXER_CONTROL" ]; then
  /bin/node /opt/beocreate/beo-system/configure.js sound mixer "$MIXER_CONTROL"
  echo " updated mixer"
  UPDATE=1
 fi 

 # Update features
 if [ "$FEATURES" != "$CURRENT_FEATURES" ]; then
  JSONFEATURES=`echo $FEATURES | sed s/\ /\",\"/g`
  JSONFEATURES="[\"$JSONFEATURES\"]"
  echo "$JSONFEATURES"
  /bin/node /opt/beocreate/beo-system/configure.js system cardFeatures $JSONFEATURES
  UPDATE=1
 fi

 # Update DSP Type
 if [ "$DSPTYPE" != "$CURRENT_DSPTYPE" ]; then
  if [ "$DSPTYPE" != "" ]; then 
   /bin/node /opt/beocreate/beo-system/configure.js system dspModel $DSPTYPE
   UPDATE=1
  fi 
 fi

 # Only change volume range if mixer control has been changed
 if [ "$SET_VOLUMERANGE" != "" -a "$CURRENT_MIXER_CONTROL" != "$MIXER_CONTROL" ]; then
  /bin/node /opt/beocreate/beo-system/configure.js sound volumeControlRange "$SET_VOLUMERANGE"
  UPDATE=1
 fi

 if [ "$UPDATE" == "1" ]; then
  restart_service beocreate2
  echo " restarting Beocreate"
 fi
}

# Reconfigure avahi
reconfigure_avahi() {
 # System name
 if [ "$SYSNAME" != "$CURRENT_SYSNAME" ]; then
   avahi-set-host-name $SYSNAME_NO_SPACES
 fi
}


# Reconfigure features
reconfigure_features() {
 # Update features in /etc/features
 if [ "$FEATURES" != "$CURRENT_FEATURES" ]; then
   rm /etc/features/*
   for f in $FEATURES; do
     touch /etc/features/$f
   done
 fi
}

MIXER_CONTROL=""
CARD="unknown"

if [ -f /etc/hifiberry.state ]; then 
. /etc/hifiberry.state
fi

if [ "$SETTINGS_LOCKED" == "yes" ]; then
  echo "Sound card settings locked, won't re-detect"
  exit
fi

if [ "$1" == "--restart-players" ]; then
 for SERVICE in $SERVICES; do
  restart_service $SERVICE
 done
 exit
fi 

read_fixed
read_features
pi_model
usb_devices
detect_hw
guess_card
guess_volume_control
system_name
check_pi3a
check_genuine

CARD_SED_SPACES=`echo $CARD | sed 's/\ /\\\\\\ /g' | sed 's/\//\\\\\\//g'` 
MIXER_SED_SPACES=`echo $MIXER_CONTROL | sed 's/\ /\\\\\\ /g' | sed 's/\//\\\\\\//g'`

FEATURES=`echo $FEATURES | xargs`

for i in $FEATURES; do 
 if [ ! -f /etc/features/$i ]; then
   echo Feature $i not yet configured
   CURRENT_FEATURES="!"
 fi
done

if [ "$HAS_DSP" == "1" ]; then
 if [ "$DSPTYPE" == "" ]; then
  DSPTYPE="$CARD"
 fi
fi

# if there is a hardware mixer, we might use this instead of DSP
if [ "$MIXER_CONTROL" == "DSPVolume" -a "$FEATURE_usehwvolume" == "1" ]; then
 if [ "$SECONDARY_MIXER_CONTROL" != "" ] && \
    [ "$SECONDARY_MIXER_CONTROL" != "Softvol" ]; then
      TMP="$MIXER_CONTROL"
      MIXER_CONTROL="$SECONDARY_MIXER_CONTROL"
      SECONDARY_MIXER_CONTROL="$TMP"
 fi
fi

# Set unused mixer controls to 100%
rm /tmp/fix-volume.done
/opt/hifiberry/bin/fix-unused-volume


if [ "$CURRENT_MIXER_CONTROL" != "$MIXER_CONTROL" ] || \
   [ "$CURRENT_CARD" != "$CARD" ] || \
   [ "$CURRENT_SYSNAME" != "$SYSNAME" ] || \
   [ "$CURRENT_PIMODEL" != "$PIMODEL" ] || \
   [ "$CURRENT_PLAYERS" != "$PLAYERS" ] || \
   [ "$CURRENT_HATINFO" != "$HATINFO" ] || \
   [ "$CURRENT_HW" != "$HW" ] || \
   [ "$CURRENT_FEATURES" != "$FEATURES" ] || \
   [ "$CURRENT_DSPTYPE" != "$DSPTYPE" ] || \
   [ "$CURRENT_INTPIN" != "$INTPIN" ] || \
   [ 1 != 1 ]; then
 echo "Sound card settings have been changed, reconfiguring..."
else
 echo "Nothing changed, exiting..."
 exit
fi

echo "Applying settings: "
echo " Players: $PLAYERS (was $CURRENT_PLAYERS)"
echo " Raspberry Pi model: $PIMODEL"
echo " System name: $SYSNAME (was $CURRENT_SYSNAME)"
echo " Sound card: $CARD (was $CURRENT_CARD)"
echo " Interrupt pin for power controller: $INTPIN (was $CURRENT_INTPIN)"
echo " DSP type: $DSPTYPE (was $CURRENT_DSPTYPE)"
echo " HW device: $HW (was $CURRENT_HW)"
echo " ALSA mixer control: $MIXER_CONTROL (was $CURRENT_MIXER_CONTROL)"
echo " Secondary mixer control: $SECONDARY_MIXER_CONTROL (was $CURRENT_SECONDARY_MIXER_CONTROL)"
echo " Recording: $CAN_RECORD (was $CURRENT_CAN_RECORD)"
echo " Vendor/product ${HATINFO} (was ${CURRENT_HATINFO})"
echo " Features: ${FEATURES} (was ${CURRENT_FEATURES})"
echo

echo "Saving settings to /etc/hifiberry.state"
echo "CURRENT_PIMODEL=$PIMODEL" > /etc/hifiberry.state
echo "CURRENT_MIXER_CONTROL=\"$MIXER_CONTROL\"" >> /etc/hifiberry.state
echo "CURRENT_SECONDARY_MIXER_CONTROL=\"$SECONDARY_MIXER_CONTROL\"" >> /etc/hifiberry.state
echo "CURRENT_CARD=\"$CARD\"" >> /etc/hifiberry.state
echo "CURRENT_HW=\"$HW\"" >> /etc/hifiberry.state
echo "CURRENT_HW_SHORT=$HW_SHORT" >> /etc/hifiberry.state
echo "CURRENT_SYSNAME=\"$SYSNAME\"" >> /etc/hifiberry.state
echo "CURRENT_PLAYERS=\"$PLAYERS\"" >> /etc/hifiberry.state
echo "CURRENT_HATINFO=\"$HATINFO\"" >> /etc/hifiberry.state
echo "CURRENT_FEATURES=\"$FEATURES\"" >> /etc/hifiberry.state
echo "CURRENT_DSPTYPE=\"$DSPTYPE\"" >> /etc/hifiberry.state
echo "CURRENT_INTPIN=\"$INTPIN\"" >> /etc/hifiberry.state
echo "PIVERSION=$PIVERSION" >> /etc/hifiberry.state

echo "Reconfigure features"
reconfigure_features
echo "Reconfiguring Spotifyd"
reconfigure_spotify
echo "Reconfiguring Vollibrespot"
reconfigure_vollibrespot
echo "Reconfiguring Shairport-sync"
reconfigure_shairport
echo "Reconfiguring Bluetooth"
reconfigure_bluetooth
echo "Reconfiguring squeezelite"
reconfigure_squeezelite
echo "Reconfiguring MPD"
reconfigure_mpd
echo "Reconfiguring DLNA"
reconfigure_dlna
echo "Reconfigure AudioControl2"
reconfigure_audiocontrol2
echo "Reconfigure upmpdcli"
reconfigure_upmpdcli
echo "Reconfigure RAAT"
reconfigure_raat
echo "Reconfiguring Beocreate software"
reconfigure_beocreate
echo "Reconfiguring avahi"
reconfigure_avahi

if [ "$1" == "--reboot" ]; then
  echo "System configuration changed" >> $REBOOTFILE
fi
